package com.yxf.variousshapes.shapes;

import android.graphics.Color;

import com.yxf.variousshapes.Point;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import static android.opengl.GLES20.GL_FLOAT;
import static android.opengl.GLES20.GL_TRIANGLE_FAN;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glVertexAttribPointer;

public class Polygon extends Shape {
    private final float radius;

    private  final int edgeCount;

    private final int pointCount;

    private float[] vertices;
    private FloatBuffer vertexData;
    private final int centerColor = Color.rgb(255, 255, 255);
    private final int circumColor = Color.rgb(0, 0, 255);

    public Polygon(Point center, float radius, int edgeCount) {
        super(center, radius * 2, radius * 2);
        this.radius = radius;
        this.edgeCount = edgeCount;
        pointCount = edgeCount + 2;

        vertices = new float[(POSITION_COMPONENT_COUNT + COLOR_COMPONENT_COUNT) * pointCount];
        int i = 0;
        //中心
        vertices[i++] = center.x;
        vertices[i++] = center.y;
        vertices[i++] = Color.red(centerColor) / 255f;
        vertices[i++] = Color.green(centerColor) / 255f;
        vertices[i++] = Color.blue(centerColor) / 255f;
        while (i < vertices.length) {
            int index = i / (POSITION_COMPONENT_COUNT + COLOR_COMPONENT_COUNT) - 1;
            double angle = Math.PI * 2 * index / this.edgeCount;
            vertices[i++] = center.x + (float) Math.cos(angle) * radius;
            vertices[i++] = center.y + (float) Math.sin(angle) * radius;
            vertices[i++] = Color.red(circumColor) / 255f;
            vertices[i++] = Color.green(circumColor) / 255f;
            vertices[i++] = Color.blue(circumColor) / 255f;
        }

        vertexData = ByteBuffer.allocateDirect(vertices.length * BYTES_PER_FLOAT)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        vertexData.put(vertices);

    }

    @Override
    public void draw() {
        vertexData.position(0);
        glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GL_FLOAT,
                false, STRIDE, vertexData);
        vertexData.position(POSITION_COMPONENT_COUNT);
        glVertexAttribPointer(aColorLocation, COLOR_COMPONENT_COUNT, GL_FLOAT,
                false, STRIDE, vertexData);

        glDrawArrays(GL_TRIANGLE_FAN, 0, pointCount);
    }
}
